package no.nordicsemi.android.nrfmesh.auth.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import java.util.ArrayList;
import java.util.List;

import no.nordicsemi.android.nrfmesh.R;
import no.nordicsemi.android.nrfmesh.auth.data.AuthRepository;
import no.nordicsemi.android.nrfmesh.auth.data.db.Account;
import no.nordicsemi.android.nrfmesh.auth.data.db.DoctorProfile;
import no.nordicsemi.android.nrfmesh.auth.data.db.UserProfile;
import no.nordicsemi.android.nrfmesh.auth.session.SessionManager;
import no.nordicsemi.android.nrfmesh.auth.ui.AuthActivity;
import no.nordicsemi.android.nrfmesh.auth.ui.AuthViewModel;
import no.nordicsemi.android.nrfmesh.database.entity.LocalAccount;
import no.nordicsemi.android.nrfmesh.widgets.CustomControlsActivity;
import no.nordicsemi.android.nrfmesh.widgets.UserMainActivity; // ← 新增：用户主页

/**
 * 登录页 Fragment
 *
 * - 支持从本机已保存账号下拉选择
 * - 默认勾选“记住到本机”，以便登录后能在“选择/管理账号”看到记录
 * - 仅在“没有被要求跳过自动登录”的情况下，才尝试静默自动登录
 */
public class LoginFragment extends Fragment {

    /** 供外部（如 AuthActivity）传参：显式跳过自动登录 */
    public static final String EXTRA_SKIP_AUTO_LOGIN = "skip_auto_login";

    private EditText etId, etPd;
    private ProgressBar progress;
    private TextView tvError;

    private AutoCompleteTextView accountSelector; // 可选控件
    private CheckBox cbRemember;                  // 默认勾选
    private CheckBox cbAutoLogin;
    private TextView tvManage;                    // “管理本机账号”

    private AuthViewModel authVM;

    // ====== 修改点：持久化的下拉数据与适配器（只创建一次，避免偶发交互失效） ======
    private final List<String> selectorIds = new ArrayList<>();
    private ArrayAdapter<String> selectorAdapter;

    @Nullable
    @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_login, container, false);

        // 原有控件
        etId = v.findViewById(R.id.etId);
        etPd = v.findViewById(R.id.etPd);
        etPd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        progress = v.findViewById(R.id.pb);
        tvError = v.findViewById(R.id.tvError);

        Button btnLogin = v.findViewById(R.id.btnLogin);
        TextView tvGotoRegister = v.findViewById(R.id.tvGotoRegister);

        // 可能新增的控件（布局里没有也没关系）
        accountSelector = v.findViewById(R.id.account_selector);
        cbRemember      = v.findViewById(R.id.cb_remember);
        cbAutoLogin     = v.findViewById(R.id.cb_auto_login);
        tvManage        = v.findViewById(R.id.tvManageAccounts);

        // 默认勾选“记住到本机”，避免你说的“列表一直是 0”
        if (cbRemember != null) cbRemember.setChecked(true);

        if (tvManage != null) tvManage.setOnClickListener(v2 -> showManageDialog());

        // ViewModel 与 Activity 共享
        authVM = new ViewModelProvider(requireActivity()).get(AuthViewModel.class);

        // ========== 1) 下拉列表绑定 ==========
        if (accountSelector != null) {
            // 修改点：适配器只创建一次，后续改变用 notifyDataSetChanged
            selectorAdapter = new ArrayAdapter<>(
                    requireContext(), android.R.layout.simple_list_item_1, selectorIds);
            accountSelector.setAdapter(selectorAdapter);

            // 修改点：点击文本或获取焦点即展开，避免“点不动”的体验
            accountSelector.setOnClickListener(vw -> accountSelector.showDropDown());
            accountSelector.setOnFocusChangeListener((vw, hasFocus) -> {
                if (hasFocus) accountSelector.showDropDown();
            });

            // 选择后回填到 etId，并标记最近使用（VM 内部会 touch + setLastUser）
            accountSelector.setOnItemClickListener((p, v1, pos, id) -> {
                String picked = (String) p.getItemAtPosition(pos);
                accountSelector.setText(picked, /*filter*/false); // 修改点：不触发再次过滤
                etId.setText(picked);
                authVM.onAuthSuccess(picked, /*displayName*/ null, /*remember*/ false, /*autoLogin*/ false);
            });

            // 监听账户列表，刷新下拉
            authVM.accounts.observe(getViewLifecycleOwner(), accounts -> {
                selectorIds.clear();
                if (accounts != null) {
                    for (LocalAccount a : accounts) selectorIds.add(a.userId);
                }
                selectorAdapter.notifyDataSetChanged();
            });
        }

        // ========== 2) 预填最近账号 ==========
        authVM.prefilledUser.observe(getViewLifecycleOwner(), u -> {
            if (u != null) {
                // 若 ID 输入框为空，预填；并同步到下拉文本，保持视觉一致
                if (etId.getText() == null || etId.getText().toString().trim().isEmpty()) {
                    etId.setText(u);
                }
                if (accountSelector != null) {
                    accountSelector.setText(u, /*filter*/false);
                }
            }
        });

        // ========== 3) 自动登录（仅在没有被要求“跳过”时进行） ==========
        boolean skipByExtra = requireActivity().getIntent().getBooleanExtra(EXTRA_SKIP_AUTO_LOGIN, false);
        boolean skipByLatchPeek = new SessionManager(requireContext()).peekSkipAutoLoginOnce();
        if (!skipByExtra && !skipByLatchPeek) {
            String autoId = authVM.tryAutoLoginUserId();
            if (autoId != null) {
                String savedPwd = authVM.getSavedPassword(autoId);
                if (savedPwd != null) { // 修改点：保护，避免 null 密码触发异常
                    performLogin(autoId, savedPwd, /*fromAutoLogin=*/true);
                }
            }
        }

        // ========== 4) 点击事件 ==========
        btnLogin.setOnClickListener(view -> doLogin());
        tvGotoRegister.setOnClickListener(view ->
                ((AuthActivity) requireActivity())
                        .goTo(new no.nordicsemi.android.nrfmesh.auth.ui.register.RolePickFragment(), true));

        return v;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 右栏文案可选中、可滚动（小屏不截断）
        TextView tvDeviceIntro = view.findViewById(R.id.tvDeviceIntro);
        TextView tvBullets = view.findViewById(R.id.tvBullets);
        TextView tvDisclaimer = view.findViewById(R.id.tvDisclaimer);
        if (tvDeviceIntro != null) {
            tvDeviceIntro.setTextIsSelectable(true);
            tvDeviceIntro.setMovementMethod(ScrollingMovementMethod.getInstance());
        }
        if (tvBullets != null) tvBullets.setTextIsSelectable(true);
        if (tvDisclaimer != null) tvDisclaimer.setTextIsSelectable(true);

        // 启动动效：卡片入场 + 经络点脉冲（MotionLayout）
        MotionLayout ml = view.findViewById(R.id.heroPane);
        if (ml != null) {
            // 延迟到布局完成后再开启动画，避免首次措位抖动
            ml.post(ml::transitionToEnd);
        }

        // TODO: 若需要“了解更多”点击，可在此添加：
        // view.findViewById(R.id.tvIntroTitle).setOnClickListener(v -> openHelp());
        // 或打开本地 PDF/网页说明。
    }
    /** 点击登录按钮入口（手动登录路径） */
    private void doLogin() {
        tvError.setText(null);
        String id = etId.getText() != null ? etId.getText().toString().trim() : "";
        String pd = etPd.getText() != null ? etPd.getText().toString() : "";

        if (id.length() < 4) { tvError.setText("ID 至少 4 位"); return; }
        if (pd.length() < 6) { tvError.setText("PD 至少 6 位"); return; }

        performLogin(id, pd, /*fromAutoLogin=*/false);
    }

    /**
     * 统一登录实现：
     * - 用 AuthRepository 校验
     * - 成功后写 Session
     * - 通知 AuthViewModel 做“记到本机/自动登录开关/刷新列表”
     * - **按角色分流到首页**：USER → UserMainActivity，DOCTOR → CustomControlsActivity
     */
    private void performLogin(String id, String pd, boolean fromAutoLogin) {
        progress.setVisibility(View.VISIBLE);

        // ====== 修改点：登录中禁用按钮，避免重复点击 ======
        View root = getView();
        Button btnLogin = root != null ? root.findViewById(R.id.btnLogin) : null;
        if (btnLogin != null) btnLogin.setEnabled(false);

        new Thread(() -> {
            try {
                AuthRepository repo = new AuthRepository(requireContext());
                Account acc = repo.login(id, pd.toCharArray());

                String displayName;
                if ("USER".equals(acc.role)) {
                    UserProfile up = repo.userProfile(acc.id);
                    displayName = up != null ? up.name : acc.username;
                } else {
                    DoctorProfile dp = repo.doctorProfile(acc.id);
                    displayName = dp != null ? dp.name : acc.username;
                }

                // 写会话（可在子线程做）
                SessionManager s = new SessionManager(requireContext());
                s.save(acc.id, acc.role, displayName);

                // 主线程：收尾、通知 VM、按角色跳转
                requireActivity().runOnUiThread(() -> {
                    boolean remember  = fromAutoLogin || (cbRemember  != null && cbRemember.isChecked());
                    boolean autoLogin = fromAutoLogin || (cbAutoLogin != null && cbAutoLogin.isChecked());

                    // 统一以“登录框输入的 id”作为保存 key，避免 username 变体
                    authVM.onLoginSucceeded(id, displayName, remember, autoLogin, pd);

                    progress.setVisibility(View.GONE);

                    Class<?> target = "USER".equals(acc.role)
                            ? UserMainActivity.class
                            : CustomControlsActivity.class;

                    startActivity(new Intent(requireContext(), target));
                    requireActivity().finish();
                });

            } catch (Exception ex) {
                requireActivity().runOnUiThread(() -> {
                    progress.setVisibility(View.GONE);
                    tvError.setText(ex.getMessage());
                    // ====== 修改点：失败恢复按钮可点 ======
                    View r = getView();
                    Button b = r != null ? r.findViewById(R.id.btnLogin) : null;
                    if (b != null) b.setEnabled(true);
                });
            }
        }).start();
    }

    /* ---------------- “管理本机账号”弹窗 ---------------- */

    private void showManageDialog() {
        List<LocalAccount> list = authVM.accounts.getValue();
        if (list == null || list.isEmpty()) {
            Toast.makeText(requireContext(), "暂无已保存账号", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] items = new String[list.size()];
        for (int i = 0; i < list.size(); i++) items[i] = list.get(i).userId;

        new android.app.AlertDialog.Builder(requireContext())
                .setTitle("本机账号")
                .setItems(items, (d, which) -> showAccountActions(list.get(which)))
                .setNegativeButton("关闭", null)
                .show();
    }

    private void showAccountActions(LocalAccount a) {
        String[] ops = new String[]{
                a.autoLogin ? "关闭自动登录" : "开启自动登录",
                "设为默认账号（下次预填）",
                "删除此账号"
        };
        new android.app.AlertDialog.Builder(requireContext())
                .setTitle(a.userId)
                .setItems(ops, (d, which) -> {
                    switch (which) {
                        case 0: // toggle auto login
                            authVM.setAccountAutoLogin(a.userId, !a.autoLogin);
                            break;
                        case 1: // set as last user（不改密文，仅设置 last_user）
                            authVM.onLoginSucceeded(a.userId,
                                    a.displayName != null ? a.displayName : a.userId,
                                    /*remember=*/true, /*autoLogin=*/a.autoLogin,
                                    /*plainPwd=*/authVM.getSavedPassword(a.userId));
                            break;
                        case 2: // delete
                            new android.app.AlertDialog.Builder(requireContext())
                                    .setMessage("确定删除「" + a.userId + "」？")
                                    .setPositiveButton("删除", (d2, w) -> authVM.deleteAccount(a.userId))
                                    .setNegativeButton("取消", null)
                                    .show();
                            break;
                    }
                })
                .setNegativeButton("返回", null)
                .show();
    }
}
